package com.zhaolang.qogir.ui.settings;

import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zhaolang.qogir.R;
import com.zhaolang.qogir.cache.SharePreCacheHelper;
import com.zhaolang.qogir.domain.Register.RegRadarReq;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.ReqFactory;
import com.zhaolang.qogir.domain.UpdateGetUser;
import com.zhaolang.qogir.domain.UpdateGetUser.GetUserReq;
import com.zhaolang.qogir.domain.UpdateGetUser.GetUserResp;
import com.zhaolang.qogir.domain.UpdateGetUser.UpdateUserResp;
import com.zhaolang.qogir.ui.ActivityTabs;
import com.zhaolang.qogir.ui.BaseFragment;
import com.zhaolang.qogir.ui.TitleView;
import com.zhaolang.qogir.ui.WelcomeLogin;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.PathUtils;
import com.zhaolang.qogir.util.PhotoUtils;
import com.zhaolang.qogir.util.SettingsInfoUtil;
import com.zhaolang.qogir.util.Slog;
import com.zhaolang.qogir.util.ToastUtils;
import com.zhaolang.qogir.view.CircularImage;

import com.zhaolang.qogir.ui.settings.FragmentSettingsList.MineGroup;
import com.zhaolang.qogir.ui.settings.FragmentSettingsList.MineItem;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class FragmentSettings extends BaseFragment implements OnClickListener {

    private static final int REQUEST_CODE_PICK_IMAGE = 111;
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 112;
    private static final int REQUEST_CODE_PICK_RESULT = 113;
    private final static int REQ_PERSONAL_INFO = 10;
    private final static int REQ_SETTING = 50;
    private final static int REQ_MESSAGE = 4;

    private static final int REQUEST_CODE_MY_DEVICE = 120;

    private FragmentSettingsList mFragmentMineList;
    private DialogHeadChange mHeadChangeDialog;
    private TitleView mTitle;
    private ImageView iv_head;
    private TextView tv_logout;

    private TextView mNickName;
    //    private TextView mGender;
//    private TextView mLevel;
//    private TextView mFollowCnt;
    private TextView mFollowedCnt;
    private View rootView;

    private UpdateGetUser mUpdateGetUser;
    private static final String IMAGE_FILE_LOCATION = PathUtils.RADAR_IMAGE_CACEH
            + "radar_temp.jpg";
    //    private static final Uri imageUri = Uri.fromFile(new File(
//            IMAGE_FILE_LOCATION));
    private static final String IMAGE_HEAD_CACHE = PathUtils.RADAR_IMAGE_CACEH
            + "radar_head_cache.jpg";

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;
    private static final int OUTPUT_X = 200;
    private static final int OUTPUT_Y = 200;

    private BaseCall<UpdateUserResp> mPortraitCallback = new BaseCall<UpdateUserResp>() {
        @Override
        public void call(UpdateUserResp resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                String portrainUrl = resp.getPortraitURL();
                Slog.d("update Portraint success and update userinfo : "
                        + HttpConstant.OFFICIAL_USER_HOST_IP + portrainUrl);
                SharePreCacheHelper.setUserIconUrl(getActivity(), HttpConstant.OFFICIAL_USER_HOST_IP + portrainUrl);
                RegRadarReq mRadarReq = new RegRadarReq();
                mRadarReq.setPortrait(portrainUrl);
                SettingsInfoUtil.reloadDefalutUserInfo(getActivity(), mRadarReq);
//                mUpdateGetUser.updateUserAsync(mRadarReq, mUserUpdateCallback);
            } else {
                Slog.e("Failed update Portrait!!!!!!!  " + resp.getMessage());
            }
            setHeadImage();
        }
    };

    private BaseCall<UpdateUserResp> mUserUpdateCallback = new BaseCall<UpdateUserResp>() {
        @Override
        public void call(UpdateUserResp resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                Slog.d("update userinfo success");
                GetUserReq mUserReq = new GetUserReq();
                mUserReq.setUserId(SharePreCacheHelper.getUserID(getActivity()));
                //mUpdateGetUser.getUserAsync(mUserReq, mUserInfoResp);
                // RegRadarReq mRadarReq = new RegRadarReq();
            } else {
                Slog.e("Failed update userinfo!!!!!!! " + resp.getMessage());
            }
        }
    };

    private BaseCall<GetUserResp> mUserInfoResp = new BaseCall<GetUserResp>() {

        @Override
        public void call(GetUserResp resp) {
            // TODO Auto-generated method stub
            if (resp == null) {
                Slog.e("Error GetUserResp == NULL!!");
            } else {
                SettingsInfoUtil.saveUserInfo(getActivity(), resp);
                handleInfoChanged();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentMineList = new FragmentSettingsList();
        mUpdateGetUser = ReqFactory.buildInterface(getActivity(),
                UpdateGetUser.class);

        addCallback(mPortraitCallback);
        addCallback(mUserInfoResp);
        addCallback(mUserUpdateCallback);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_settings, null);
            init_view();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    private void init_view() {
        iv_head = (CircularImage) rootView.findViewById(R.id.iv_head);
        mNickName = (TextView) rootView.findViewById(R.id.tv_nickname);
        tv_logout = rootView.findViewById(R.id.tv_logout);
        iv_head.setOnClickListener(this);
        tv_logout.setOnClickListener(this);

        FragmentManager cfm = getChildFragmentManager();
        if (null == cfm.findFragmentByTag("mineList")
                || !mFragmentMineList.isInLayout()) {
            mFragmentMineList.setGroups(genGroups());
            getChildFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, mFragmentMineList,
                            "mineList").commit();
        }
        mHeadChangeDialog = new DialogHeadChange(getActivity());
        mHeadChangeDialog.setButtonsOnClickListener(this, this, this);
    }

    private void handleInfoChanged() {
        String iconUrl = SharePreCacheHelper.getUserIconUrl(getActivity());
        if (TextUtils.isEmpty(iconUrl)) {
            iv_head.setImageResource(R.drawable.logo_arabitiacafe);
        } else {
            if (iconUrl.startsWith("http")) {
                SettingsInfoUtil.setImageFromUrl(iconUrl, iv_head);
            } else {
                SettingsInfoUtil.setImageFromUrl(
                        HttpConstant.OFFICIAL_RADAR_DOWNLOAD_IMG_IP + iconUrl,
                        iv_head);
            }
        }

        String sparam = SharePreCacheHelper.getNickname(getActivity());
        if (!TextUtils.isEmpty(sparam)) {
            mNickName.setText(sparam);
        } else {
            mNickName.setText(getResources().getString(R.string.ui_settings_string_shop_name));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        handleInfoChanged();
        GetUserReq mUserReq = new GetUserReq();
        mUserReq.setUserId(SharePreCacheHelper.getUserID(getActivity()));
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void setHeadImage() {
        String iconUrl = SharePreCacheHelper.getUserIconUrl(getActivity());
        if (TextUtils.isEmpty(iconUrl)) {
            iv_head.setImageResource(R.drawable.logo_arabitiacafe);
        } else {
            if (iconUrl.startsWith("http")) {
                SettingsInfoUtil.setImageFromUrl(iconUrl, iv_head);
            } else {
                SettingsInfoUtil.setImageFromUrl(
                        HttpConstant.OFFICIAL_RADAR_DOWNLOAD_IMG_IP + iconUrl,
                        iv_head);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case TitleView.ID_LEFT:
//                Intent intent1 = new Intent(mContext, ActivityMyMessage.class);
//                startActivityForResult(intent1, REQ_MESSAGE);
                break;
            case R.id.iv_head:
                mHeadChangeDialog.show();
                break;
            case DialogHeadChange.ID_PHOTO:
                mHeadChangeDialog.dismiss();
                autoObtainStoragePermission();
                break;
            case DialogHeadChange.ID_TAKIN:
                mHeadChangeDialog.dismiss();
                autoObtainCameraPermission();
                break;
            case DialogHeadChange.ID_CANCEL:
                mHeadChangeDialog.dismiss();
                break;
            case R.id.tv_logout:
//                SharePreCacheHelper.setUserName(mContext, "");
////                RadarProxy.getInstance(getApplicationContext()).startLocalData(HttpConstant.DELETE_ALL_LOCAL_SENDING_POST, null, null);
//                Intent intent = new Intent(mContext, WelcomeLogin.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//                startActivity(intent);
                break;
            case R.string.settings_printer_manage:
                startActivity(new Intent(mContext, ActivitySettingsPrinter.class));
                break;
            case R.string.settings_order_taking_st:
                startActivity(new Intent(mContext, ActivityOrderManage.class));
                break;
            default:
                break;
        }
    }

    private boolean saveImage(Bitmap photo, String spath) {
        try {
            File file = new File(spath);
            File parant = file.getParentFile();
            if (!parant.exists()) {
                parant.mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
//            file.createNewFile();
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(spath, false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            Slog.e("", e);
            return false;
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Slog.d("onActivityResult: requestCode: " + requestCode + "  resultCode:" + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            Slog.e("onActivityResult: resultCode!=RESULT_OK");
            return;
        }
        switch (requestCode) {
            //相机返回
            case CODE_CAMERA_REQUEST:
                cropImageUri = Uri.fromFile(fileCropUri);
                PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                break;
            //相册返回
            case CODE_GALLERY_REQUEST:
                if (hasSdcard()) {
                    Slog.d("CODE_GALLERY_REQUEST request");
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtils.getPath(getActivity(), data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(getActivity(), "com.zz.fileprovider", new File(newUri.getPath()));
                    }
                    Slog.d("start to crop image uri");
                    PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                } else {
                    ToastUtils.showShort(getActivity(), "设备没有SD卡！");
                }
                break;
            //裁剪返回
            case CODE_RESULT_REQUEST:
                Bitmap photo = PhotoUtils.getBitmapFromUri(cropImageUri, getActivity());
                if (photo != null) {
                    iv_head.setImageBitmap(photo);
                    Slog.w("update portrait : " + fileCropUri);
                    Slog.w("update portrait string path : " + fileCropUri.toString());
                    saveImage(photo, fileCropUri.toString());
                    List<String> mimgs = new ArrayList<String>();
                    mimgs.add(fileCropUri.toString());
                    mUpdateGetUser.uploadPortraitAsync(mimgs, mPortraitCallback);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Slog.d("onRequestPermissionsResult: ");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //调用系统相机申请拍照权限回调
            case CAMERA_PERMISSIONS_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            //通过FileProvider创建一个content类型的Uri
                            imageUri = FileProvider.getUriForFile(getActivity(), "com.zz.fileprovider", fileUri);
                        }
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        ToastUtils.showShort(getActivity(), "设备没有SD卡！");
                    }
                } else {
                    ToastUtils.showShort(getActivity(), "请允许打开相机！！");
                }
                break;
            }
            //调用系统相册申请Sdcard权限回调
            case STORAGE_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {
                    ToastUtils.showShort(getActivity(), "请允许打操作SDCard！！");
                }
                break;
            default:
        }
    }

    private List<MineGroup> genGroups() {
        List<MineGroup> groups = new ArrayList<MineGroup>(3);

        List<MineItem> is1 = new ArrayList<MineItem>(2);
        is1.add(new MineItem(R.string.settings_notify_center,
                R.drawable.main_icon_setting_notice, R.string.settings_notify_center,
                false, true, this));
        groups.add(new MineGroup(true, true, true, is1));

        List<MineItem> is2 = new ArrayList<MineItem>(2);
        is2.add(new MineItem(R.string.settings_order_taking_st, R.drawable.main_icon_setting_order,
                R.string.settings_order_taking_st, false, true, this));

        is2.add(new MineItem(R.string.settings_wechat_assistant, R.drawable.main_icon_setting_wechat,
                R.string.settings_wechat_assistant, false, true, this));

        is2.add(new MineItem(R.string.settings_printer_manage, R.drawable.main_icon_setting_printer,
                R.string.settings_printer_manage, false, true, this));

        is2.add(new MineItem(R.string.settings_realtime_message, R.drawable.main_icon_setting_feedback,
                R.string.settings_realtime_message, false, true, this));

        groups.add(new MineGroup(true, true, true, is2));

        List<MineItem> is3 = new ArrayList<MineItem>(1);
        is3.add(new MineItem(R.string.settings_help_feedback,
                R.drawable.main_icon_setting_feedback, R.string.settings_help_feedback, false,
                true, this));

        is3.add(new MineItem(R.string.settings_online_service,
                R.drawable.main_icon_setting_online_service, R.string.settings_online_service, false,
                true, this));

        is3.add(new MineItem(R.string.settings_call_service,
                R.drawable.main_icon_setting_service_center, R.string.settings_call_service, false,
                true, this));

        is3.add(new MineItem(R.string.settings_market_manager,
                R.drawable.main_icon_setting_market_manager, R.string.settings_market_manager, false,
                true, this));
        groups.add(new MineGroup(true, true, true, is3));


        List<MineItem> is4 = new ArrayList<MineItem>(1);
        is4.add(new MineItem(R.string.settings_account_security,
                R.drawable.main_icon_setting_user_info, R.string.settings_account_security, false,
                true, this));

        is4.add(new MineItem(R.string.settings_operation_logger,
                R.drawable.main_icon_setting_order, R.string.settings_operation_logger, false,
                true, this));

        is4.add(new MineItem(R.string.settings_rule_center,
                R.drawable.main_icon_setting_rule_center, R.string.settings_rule_center, false,
                true, this));

        is4.add(new MineItem(R.string.settings_about_us,
                R.drawable.main_icon_setting_about_us, R.string.settings_about_us, false,
                true, this));
        groups.add(new MineGroup(true, true, true, is4));

        return groups;
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 动态申请sdcard读写权限
     */
    private void autoObtainStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
            } else {
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
            }
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }
    }

    /**
     * 申请访问相机权限
     */
    private void autoObtainCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                    ToastUtils.showShort(getActivity(), "您已经拒绝过一次");
                }
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
            } else {//有权限直接调用系统相机拍照
                if (hasSdcard()) {
                    imageUri = Uri.fromFile(fileUri);
                    //通过FileProvider创建一个content类型的Uri
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        imageUri = FileProvider.getUriForFile(getActivity(), "com.zz.fileprovider", fileUri);
                    }
                    PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                } else {
                    ToastUtils.showShort(getActivity(), "设备没有SD卡！");
                }
            }
        }
    }
}


